package com.gudaomai.wuye.pdf;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

public class PdfGenerator {

	public static File getPdf(Bill bill) throws Exception {
		
		Document document = new Document();
		PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("pdf.pdf"));
		document.open();
		XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream(getHtmlBill(bill)));
		document.close();

		File pdf = new File("pdf.pdf");
		if (pdf.exists()) {
			return pdf;
		}else {
			throw new FileNotFoundException();
		}
	}

	private static File getHtmlBill(Bill bill) {

		StringBuilder builder = new StringBuilder();
		// TODO 加入css文件,文件名或有变更,index.css的文件的位置
		builder.append("<!doctype html>").append("<html>").append("<head>").append("<title>").append("BILL HTML")
				.append("</title>").append("<link href='index.css' rel='stylesheet' type='text/css' />")
				.append("</head>").append("<body>");
		// TODO bill里存有的字段
		builder.append("</table>").append(
				"<tr><th>收费名称</th><th>起始时间</th><th>结束时间</th><th>起数</th><th>止数</th><th>单价</th><th>单位</th><th>起始时间</th><th>周期</th><th>期数</th><th>滞纳金</th><th>应收金额</th><th>实收金额</th><th>备注</th></tr>");
		for (Element e : bill.getElements()) {
			builder.append("<tr>").append("<td>" + e.getChargeName() + "</td>")
					.append("<td>" + e.getStartTime() + "</td>").append("<td>" + e.getEndTime() + "</td>")
					.append("<td>" + e.getStartNumber() + "</td>").append("<td>" + e.getEndNumber() + "</td>")
					.append("<td>" + e.getPrice() + "</td>").append("<td>" + e.getPriceUnit() + "</td>")
					.append("<td>" + e.getCycle() + "</td>").append("<td>" + e.getCycleNumber() + "</td>")
					.append("<td>" + e.getLaterMoney() + "</td>").append("<td>" + e.getNeedReceiveMoney() + "</td>")
					.append("<td>" + e.getRealReceiveMoney() + "</td>").append("<td>" + e.getDescribe() + "</td>");
		}

		builder.append("</table>")
				// TODO bill里存在的字段
				.append("</body>").append("</html>");

		File html = new File("index.html");
		if (!html.exists()) {
			try {
				html.createNewFile();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

		BufferedWriter writer = null;

		try {
			writer = new BufferedWriter(new FileWriter(html));
			writer.write(builder.toString());

		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

		return html;
	}

}
